#include "core\Text.h"

FontManager* FontManager::getInstance()
{
  static FontManager instance;
  return &instance;
}

FontManager::FontManager()
{
  m_hDC = 0;
}

FontManager::~FontManager()
{  
  for(fontMap::iterator it=fonts.begin();it!=fonts.end();it++) freeFont((*it).first);
}

bool FontManager::loadFont(std::string name, std::string font, int height, bool italic, bool underline, bool strikeout)
{
  if(m_hDC == 0) return false; 
  Font f;
  f.base = glGenLists(96);
  HFONT hFont = CreateFont(-height, 0, 0, 0, FW_BOLD, italic, underline, strikeout, ANSI_CHARSET, OUT_TT_PRECIS, CLIP_DEFAULT_PRECIS,
    ANTIALIASED_QUALITY, FF_DONTCARE | DEFAULT_PITCH, font.c_str());
  if(hFont == 0) return false;
  HFONT temp = (HFONT)SelectObject(m_hDC, hFont);
  wglUseFontBitmaps(m_hDC, 32, 96, f.base);
  SelectObject(m_hDC, temp);
  DeleteObject(hFont);
  fonts[name] = f;
  return true;
}

void FontManager::freeFont(std::string name)
{
  glDeleteLists(fonts[name].base, 96);
}

void FontManager::print(std::string font, const char* fmt, ...)
{
  char text[512];
  va_list ap;
  if(fmt == 0) return;
  va_start(ap, fmt);
  vsprintf(text, fmt, ap);
  va_end(ap);
  glPushAttrib(GL_LIST_BIT);
  glListBase(fonts[font].base - 32);
  glCallLists(strlen(text), GL_UNSIGNED_BYTE, text);
  glPopAttrib();
}

void FontManager::setHDC(HDC hDC)
{
  m_hDC = hDC;
}